<template>
  <div class="page-demand">
    <!-- 顶部导航 -->
    <div class="flex items-center justify-between h-16 bg-white border-b border-gray-200" style="margin-top: -50px;">
      <div class="flex items-center space-x-4">
        <el-icon
          class="text-orange-500 cursor-pointer text-xl" @click="back"
          style="color: #409eff; font-weight: bold; font-size: 26px;">
          <ArrowLeft/>
        </el-icon>
        <span class="text-gray-700 font-color" style="font-size: 16px;">{{
            formData.enterpriseName
          }}</span>
        <span class="text-gray-500 ml-8 font-color" style="font-size: 16px;">{{
            formData.demandCode
          }}</span>
      </div>

      <div class="flex items-center space-x-4">
        <span class="text-gray-600" style="font-size: 16px;" v-if="formData.status != '已关闭'">审核人：{{
            formData.approver || '--'
          }}</span>
        <span
class="text-gray-400" style="font-size: 16px;"
              v-if="formData.status != '已关闭'">|</span>
        <span class="text-gray-600" style="font-size: 16px;" v-if="formData.status != '已关闭'">审核时间：{{
            formData.approverTime ? formatTime(formData.approverTime) : '--'
          }}</span>
        <span class="text-gray-600" style="font-size: 16px;" v-if="formData.status === '已完成'">完成时间：{{
            formData.approverTime ? formatTime(formData.updateTime) : '--'
          }}</span>


        <div class="flex items-center space-x-3 ml-8">

          <div class="dialog-footer">
            <div v-if="formData.status === '待确认'">
              <el-button
                @click="submitForm(1)"
                :disabled="formLoading || !userInfo.roles?.some(role => role.shtg === 'true')"
                class="!rounded-button whitespace-nowrap" type="primary">
                审核通过
              </el-button>
              <el-button
                @click="showRejectDialog"
                :disabled="formLoading || !userInfo.roles?.some(role => role.shbh === 'true')"
                class="!rounded-button whitespace-nowrap" type="danger">
                审核不通过
              </el-button>
            </div>
            <div v-if="formData.status === '已确认'">
              <el-button
                @click="submitForm(3)"
                :disabled="formLoading || !userInfo.roles?.some(role => role.gbxq === 'true')"
                class="!rounded-button whitespace-nowrap" type="default">
                关闭需求
              </el-button>
              <el-button
                @click="submitForm(4)"
                :disabled="formLoading || !userInfo.roles?.some(role => role.bc === 'true')"
                class="!rounded-button whitespace-nowrap" plain type="success">
                保存
              </el-button>
              <el-button
                @click="submitForm(5)"
                :disabled="formLoading || !userInfo.roles?.some(role => role.xqwc === 'true')"
                class="!rounded-button whitespace-nowrap" type="success">
                需求完成
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="label bg-color">需求详情</div>
    <div class="bd-dj" style="position: relative;">
      <span
        class="text-gray-600"
        :style="{ color: getStatusColor(formData.status), position: 'absolute', top: '8px', right: '8px' }"
      >{{ formData.status }}</span>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-row style="width: 100%">
          <el-form-item label="需求名称" prop="demandName" class="custom-label-size">
            <el-input
v-if="formData.status === '待确认'" v-model="formData.demandName"
                      style="width: 1000px; padding: 0;"  class="small-height-input"  @change="submitForm(6)"/>
            <span v-else class="small-height-text">{{ formData.demandName || '--' }}</span>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%">
          <el-form-item label="发布时间" prop="demandName" class="custom-label-size">
            <span style="font-size: 16px;">{{ formData.createTime ? formatTime(formData.createTime) : '--' }}</span>
          </el-form-item>
        </el-row>
        <el-row style="width: 100%">
          <el-form-item label="需求描述" prop="demandName" class="custom-label-size">

            <el-input
              v-if="formData.status === '待确认'"
              v-model="formData.demandDescription"
              type="textarea"
              :rows="4"
              style="width: 1000px;font-size: 16px;"
              @change="submitForm(6)"
            />
            <span v-else>{{ formData.demandDescription || '--' }}</span>
          </el-form-item>
        </el-row>

        <el-row :style="`width: 100%; margin-top: ${ formData.status === '待确认' ? '10px' : '0' }`" v-if="formData.status != '已完成'">
          <el-form-item label="交易单元" prop="demandDescription" class="custom-label-size">
            <!-- 循环展示单元 -->
            <div
v-for="(item, index) in formData.demandInfoTradingUnitMapList" :key="index"
                 class="flex items-center">
              <span style="font-size: 15px;">{{ item.tradingUnitName }}-{{ item.tradingUnit }}</span>&nbsp;&nbsp;
            </div>&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button
v-if="formData.status === '待确认'" type="primary"
                       @click="showTradingUnitDialog">编辑交易单元
            </el-button>


            <!-- 交易单元选择对话框 -->
            <el-dialog v-model="tradingUnitDialogVisible" title="选择交易单元">
              <el-checkbox-group v-model="selectedTradingUnitIds">
                <el-checkbox v-for="unit in allTradingUnits" :key="unit.id" :label="unit.id">
                  {{ unit.name }}-{{ unit.tradingUnit }}
                </el-checkbox>
              </el-checkbox-group>
              <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="tradingUnitDialogVisible = false">取消</el-button>
                      <el-button
type="primary"
                                 @click="confirmTradingUnitSelection">确定</el-button>
                    </span>
              </template>
            </el-dialog>
          </el-form-item>
        </el-row>

        <el-row style="width: 100%" v-if="formData.status === '已完成'">
          <el-form-item label="交易单元" prop="demandDescription"  class="custom-label-size">
            <!-- 循环展示单元 -->
            <div
v-for="(item, index) in unitList" :key="index"
                 class="flex items-center">
                 <span style="font-size: 16px;">{{item.tradingUnitName}} - {{ item.tradingUnit}}</span>
            </div>&nbsp;&nbsp;&nbsp;&nbsp;
            <el-button
v-if="formData.status === '待确认'" type="primary"
                       @click="showTradingUnitDialog">编辑交易单元
            </el-button>

          </el-form-item>
        </el-row>

        <el-row style="width: 100%; max-height: 170px; overflow-y: auto;">

          <el-form-item
            label-width="100px" prop="demandDescription"
            class="d-form-item custom-label-size"
            v-if="formData.status === '已确认' || formData.status === '已完成' || formData.status === '待确认'">
             <!-- 添加刷新按钮 -->
             <!-- <el-button @click="refreshData" type="primary" size="small">刷新</el-button> -->
            <!-- 后续表单内容 -->
              <!-- 使用 label 插槽添加换行标签 -->
            <template #label>
              操作电量<br/>(MWh)
            </template>
            <el-row
              v-for="(item, index) in formData.demandInfoTradingUnitMapList" :key="index"
              style="width: 100%;">
              <el-row
                style="width: 100%; display: flex; flex-wrap: nowrap; align-items: flex-start;">
                <el-col :span="2">
                  <h3 class="custom-h3-size" v-html="`${item.tradingUnitName}<br>${item.tradingUnit}`"></h3>
                </el-col>
                <el-col :span="18">
                  <el-row v-for="(unitDo, index2) in item.demandInfoTradingUnitDO" :key="index2" style="display: flex;">
                    <el-col :span="2">
                      <h3 class="custom-h3-size">{{
                          unitDo.type ? [{label: '转入', value: '1'}, {
                            label: '转出',
                            value: '2'
                          }].find(child => child.value === unitDo.type).label : ''
                        }}</h3>
                    </el-col>
                    <el-col :span="10">
                      <el-row>
                        <h3 class="custom-h3-size" style="margin-right: 20px;">峰：{{ Number(unitDo.feng).toFixed(3) }}</h3>
                        <h3 class="custom-h3-size" style="margin-right: 20px;">&nbsp;&nbsp;平：{{ Number(unitDo.ping).toFixed(3) }}</h3>
                        <h3 class="custom-h3-size" style="margin-right: 20px;">&nbsp;&nbsp;谷：{{ Number(unitDo.gu).toFixed(3) }}</h3>
                        <h3 class="custom-h3-size">&nbsp;&nbsp;总：{{ Number(unitDo.zong).toFixed(3) }}</h3>
                      </el-row>
                    </el-col>
                    <el-col :span="5">
                      <h3 class="custom-h3-size">预计操作日期：{{
                          unitDo.expectedDate ? unitDo.expectedDate.replace(/T/g, ' ').replace(/\.000Z/g, '') : ''
                        }}</h3>
                    </el-col>
                    <el-col :span="4">
                      <h3 class="custom-h3-size no-wrap">转让对象：{{
                          unitDo.participateTradingDo ? unitDo.participateTradingDo.tradingUnit : unitDo.notTrading
                        }}</h3>
                    </el-col>
                  </el-row>
                </el-col>

              </el-row>

            </el-row>
          </el-form-item>

        </el-row>

      </el-form>
    </div>

    <!-- 审核不通过 -->
    <el-row title="未审核通过" v-if="formData.status === '未审核通过'" width="30%">
      <span style="color: red;">审核不通过的原因：{{ formData.notPassing || '--' }}</span>
    </el-row>


    <el-tabs
      v-model="editableTabsValue"
      type="card"
      class="demo-tabs"
      @tab-change="tabChange"
      v-if="formData.status != '未审核通过' && formData.status != '已关闭'"
      style="height: auto; min-height: 0;"
    >
      <el-tab-pane
        v-for="item in unitList"
        :key="item.tradingUnitId"
        :label="item.tradingUnitName+ '——' +item.tradingUnit"
        :name="item.tradingUnitId"
      >
        <!-- 根据不同的 tab 显示不同的组件 -->
        <component
          ref="detailTable" :is="getTabComponent(item.tradingUnitId)" :formType="formType"
          :tradingUnitId="item.tradingUnitId" :mainId="mainId" :tableList="tableList"
          :zhuanrangriqiList="zhuanrangriqiList" @get-date-list="getDateList"
          @get-data-list="openData"
          @submit-form="submitForm"
          @update-transferor-img="updateTransferorImgInParent"
          @update-feng-value="updateFengValueInParent"
          />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup lang="ts">
import {DemandInfoMainApi, DemandInfoMainVO} from '@/api/dd/demandinfomain'
import {DemandInfoTradingUnitApi, DemandInfoTradingUnitVO} from '@/api/dd/demandinfotradingunit'
import {getUserProfile} from '@/api/system/user/profile'
import {ref, getCurrentInstance} from 'vue'
import daiquerenTable from "@/views/dd/demandinfomain/daiqueren-table.vue";
import yiquerenTable from "@/views/dd/demandinfomain/yiqueren-table.vue";
import yiwanchengTable from "@/views/dd/demandinfomain/yiwancheng-table.vue";
import {TradingUnitApi} from "@/api/dd/tradingunit";
import detailsTable from "@/views/dd/demandinfomain/details-table.vue";
import {ArrowLeft} from '@element-plus/icons-vue';

// 用于存储每个标签页的数据
const tabDataMap = reactive({});

// 保存当前数据并切换标签页
const saveCurrentDataAndChangeTab = (tradingUnitId: number) => {
  // 保存当前标签页的数据
  console.log(tabDataMap, 'tabDataMap')
  console.log(tradingUnitId, 'tradingUnitId.value')
  if (editableTabsValue.value) {
    tabDataMap[editableTabsValue.value] = {
      tableList: tableList.value,
      // 可以根据需要添加更多需要保存的数据
    };
  }

  // 切换标签页
  editableTabsValue.value = tradingUnitId;

  // 检查是否有之前保存的数据，如果有则恢复
  if (tabDataMap[tradingUnitId]) {
    tableList.value = tabDataMap[tradingUnitId].tableList;
    // 恢复其他保存的数据
  }
};


/** 需求信息主 表单 */
defineOptions({name: 'DialogDemandInfoMainForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const route = useRoute()

const formData = ref({
  id: undefined,
  demandCode: undefined,
  enterpriseId: undefined,
  enterpriseName: undefined,
  demandName: undefined,
  demandDescription: undefined,
  status: undefined,
  notPassing: undefined,
  createTime: undefined
})
const formRules = reactive({
  name: [
    {required: true, message: 'Please input Activity name', trigger: 'blur'},
    {min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur'},
  ],
})
const formRef = ref() // 表单 Ref
const mainId = ref()
const formDataList = ref([])

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type: number, isFresh: boolean = false) => {
  console.log(type, 'type.value.')
  if(type == 6){
    const data = formData.value as unknown as DemandInfoMainVO
    await DemandInfoMainApi.updateDemandInfoMain(data)
  }
  //审核不通过
  if (type == 2) {
    // console.log(formData.value, ' formData.value')
    const enum_ = {
      1: '已确认',
      2: '未审核通过',
      3: '已关闭',
      4: formData.value.status,
      5: '已完成',
    }
    formData.value.status = enum_[type]
    // console.log(formData.value, 'formData.value')
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as DemandInfoMainVO
      console.log(data, 'data')
      //判断必填数据不能为空
      if (formType.value === 'create') {
        await DemandInfoMainApi.createDemandInfoMain(data)
        message.success(t('common.createSuccess'))
      } else {
        await DemandInfoMainApi.updateDemandInfoMain(data)
        message.success(t('common.updateSuccess'))
      }
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
      router.back()
    } finally {
      formLoading.value = false
    }
  } else {
    if (type == 1) {
      // await formRef.value.validate()
      await open(formType.value, route.query.id)
      console.log(detailTable.value, 'detailTable.value')

      function ddd() {
        return new Promise((resolve, reject) => {
          let searchArr = []
          let table = []
          for (const item of detailTable.value) {
            for (const child of item.dataFormList.data) {
              if (child.radio == 1) {
                if (!child.participateTradingId) {
                  searchArr.push('有未填写信息的交易单元，请补充完成或删除该交易单元后进行审核。')
                }
              } else if (child.radio == 2) {
                if (!child.notTrading) {
                  searchArr.push('我方不参与不能为空')
                }
              }
              if(!child.expectedDate){
                searchArr.push('预计操作日期不能为空')
              }
            }
            for (const child of item.tableList) {
              const someOne = child.demandInfoTradingUnitInformationControllers.some(cd => cd.electricity && cd.electricityPrice)
              if (!someOne) {
                table.push(1)
              }
            }
          }
          if (searchArr.length) {
            reject(searchArr[0])
          } else if (table.length) {
            reject(searchArr[0])
          } else {
            resolve()
          }
        })
      }
      ddd().then((msg: any) => {
        ElMessageBox.confirm('是否确认通过审核？').then(async () => {
          if (msg) {
          ElMessageBox.confirm(msg).then(async () => {
            submitGongGong(type);
          }).catch(() => {
          })
        } else {
          submitGongGong(type);
        }
          }).catch(() => {

          })

      }).catch(type => {
        console.log(type, 'type')
        if (type === 1) {
          message.error('查询条件必填！')
        } else {
          message.error('有未填写信息的交易单元，请补充完成或删除该交易单元后进行审核！')
        }
      })
    } else {
      if (isEmpty()) {
        if (type == 5) {
          // const isPass = validateRequired()
          console.log(detailTable.value, 'detailTable.value')
          // 判断 transfereeImg 是否为空
          let allTransfereeImgEmpty = true;
          let allTransferorImg  = true;
          let allPaymentImg = true;
          if (detailTable.value) {
            for (const item of detailTable.value) {
              for (const child of item.dataFormList.data) {
                if (child.transfereeImg && child.transfereeImg.length > 0) {
                  allTransfereeImgEmpty = false;
                  break;
                }
                if (child.transferorImg && child.transferorImg.length > 0) {
                  allTransferorImg = false;
                  break;
                }

                if (child.paymentImg && child.paymentImg.length > 0) {
                  allPaymentImg = false;
                  break;
                }

              }
              if (!allTransfereeImgEmpty) {
                break;
              }
            }
          }
          function ddd() {
            return new Promise((resolve, reject) => {
              let searchArr = []
              let table = []
              for (const item of detailTable.value) {
                for (const child of item.dataFormList.data) {
                  if (child.radio == 1) {
                    if (!child.participateTradingId) {
                      searchArr.push('有未填写信息的交易单元，请补充完成或删除该交易单元后进行审核。')
                    }
                  } else if (child.radio == 2) {
                    if (!child.notTrading) {
                      searchArr.push('我方不参与不能为空')
                    }
                  }
                }
                for (const child of item.tableList) {
                  const someOne = child.demandInfoTradingUnitInformationControllers.some(cd => cd.electricity && cd.electricityPrice)
                  if (!someOne) {
                    table.push(1)
                  }
                }
              }
              if (searchArr.length) {
                reject(searchArr[0])
              } else if (table.length) {
                reject(searchArr[0])
              } else {
                resolve()
              }
            })
          }
          ddd().then((msg: any) => {
            if (!msg) {
              if(allTransfereeImgEmpty && allTransferorImg && allPaymentImg){
                ElMessageBox.confirm('您有未上传完整的信息，是否完成需求？').then(async () => {
                  submitGongGong(type);
                }).catch(() => {});
              }else{
                ElMessageBox.confirm('请务必确认当前需求中所有交易电量已在交易中心完成持仓变更。').then(async () => {
                  submitGongGong(type);
                }).catch(() => {

                })
              }
            }
          }).catch(type => {
            // console.log(type, 'type')
            if (type === 1) {
              message.error('查询条件必填！')
            } else {
              message.error('有未填写信息的交易单元，请补充完成或删除该交易单元后进行审核！')
            }
          })
          // if (!isPass) {
          //   // ElMessageBox.confirm('您有未上传完整的信息，是否完成需求？是否确认操作？').then(async () => {
          //   //   submitGongGong(type);
          //   // }).catch(() => {

          //   // })
          //   ElMessageBox.confirm('请务必确认当前需求中所有交易电量已在交易中心完成持仓变更。').then(async () => {
          //     submitGongGong(type);
          //   }).catch(() => {

          //   })


          // }
        } else if (type == 3) {
          ElMessageBox.confirm('是否确认操作？').then(async () => {
            // 校验表单
            await formRef.value.validate()
            // console.log(formData.value, ' formData.value')
            const enum_ = {
              1: '已确认',
              2: '未审核通过',
              3: '已关闭',
              4: formData.value.status,
              5: '已完成',
            }
            formData.value.status = enum_[type]
            // console.log(formData.value, 'formData.value')
            // 提交请求
            formLoading.value = true
            try {
              const data = formData.value as unknown as DemandInfoMainVO
              console.log(data, 'data')
              //判断必填数据不能为空
              if (formType.value === 'create') {
                await DemandInfoMainApi.createDemandInfoMain(data)
                message.success(t('common.createSuccess'))
              } else {
                await DemandInfoMainApi.updateDemandInfoMain(data)
                message.success(t('common.updateSuccess'))
              }
              dialogVisible.value = false
              // 发送操作成功的事件
              emit('success')
              router.back()
            } finally {
              formLoading.value = false
            }
          }).catch(() => {

          })
        } else if (type === 4) {
          (formData.value as any).demandInfoTradingUnitMapList = (formData.value as any).demandInfoTradingUnitMapList.map(item => {
            const list = detailTable.value.filter(child => child.tradingUnitId === editableTabsValue.value)
            // console.log(list, 'detailTable.value.filter(child => child.tradingUnitId === editableTabsValue.value)')
            if (list.length) {
              item.demandInfoTradingUnitDO = list[0].tableList
              return item
            }
            return item
          })

          if (isFresh) {
            submitGongGong(type, isFresh);
          } else {

            ElMessageBox.confirm('是否保存当前信息？').then(async () => {
              submitGongGong(type, isFresh);
            }).catch(() => {

            })
          }
        }
      }
    }

  }


}

const detailTable: any = ref(null)
// 表格必填校验
const validateRequired = () => {
  let isPass = true

  for (let i = 0; i < detailTable.value.length; i++) {
    const item: any = detailTable.value[i]

    for (let j = 0; j < item.dataFormList.data.length; j++) {
      const child = item.dataFormList.data[j]
      if (!child.transferDateStart || !child.transferDateEnd) {

        console.log(child, 'child')

        if (!child.transferDateStart || !child.transferDateEnd) {
          message.error('请填写转让日期')
          return false
        }
        return false
      }
    }
    //参与交易单元不能为空
    for (let j = 0; j < item.dataFormList.data.length; j++) {
      const child = item.dataFormList.data[j]
      if (!child.transferDateStart || !child.transferDateEnd) {

        console.log(child, 'child')

        if (!child.transferDateStart || !child.transferDateEnd) {
          // message.error('请填写转让日期')
          return false
        }
        return false
      }
    }
    for (let j = 0; j < item.tableList.length; j++) {
      const child = item.tableList[j]

      for (let k = 0; k < child.demandInfoTradingUnitInformationControllers.length; k++) {

        if (child.demandInfoTradingUnitInformationControllers.some(son => son.actualAmount || son.electricityPrice)) {
          return false
        }

        // const son = child.demandInfoTradingUnitInformationControllers[k]
        //
        // console.log(son, 'son')
        //
        // if (!son.electricity || !son.electricityPrice) {
        //   // message.error('请填写必填项')
        //   return false
        // }

      }

    }

  }

  return isPass

}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    demandCode: undefined,
    enterpriseId: undefined,
    enterpriseName: undefined,
    demandName: undefined,
    demandDescription: undefined,
    status: undefined,
    notPassing: undefined,
  }
  formRef.value?.resetFields()
}

//交易单元
const unitList = ref<DemandInfoTradingUnitVO[]>([])

/** 选择交易单元 */
const editableTabsValue: any = ref('')
const editableTabs: any = ref([])

// 表格列表
const tableList = ref('')

// 转让日期
const zhuanrangriqiList = ref([])

// 获取转让日期列表
const getDateList = () => {
  DemandInfoMainApi.getDateListApi({
    unitId: editableTabsValue.value,
    id: mainId.value
  }).then(res => {

    zhuanrangriqiList.value = res.data.filter(item => item).map(item => {
      return item.replace(/T/g, ' ').replace(/\.000Z/g, '');
    })
  })
}

const tabChange = async (tradingUnitId: number) => {
  console.log(tradingUnitId, `id=${tradingUnitId}`, unitList.value)
  editableTabsValue.value = tradingUnitId
  //切换是获取当前页面的表格的数据
  const canyujiaoyidanyuan = await TradingUnitApi.getTradingUnitSelect()

  nextTick(() => {
    tableList.value = (unitList.value as any).filter(item => item.tradingUnitId === tradingUnitId)[0].demandInfoTradingUnitDO.map(item => {
      return {
        ...item,
        radio: item.participateTradingId ? '1' : (item.notTrading ? '2' : '1'),
        canyujiaoyidanyuan,
        change: (val, item) => {
          if (val === '1') {
            item.notTrading = ''
          } else {
            item.participateTradingId = ''
          }
        },
      }
    })
    getDateList()
  })
  // console.log(tableList, 'tableList.value')
}
const removeTab = (tradingUnitId: number) => {
  const tabs = editableTabs.value
  let activeId = editableTabsValue.value
  if (activeId === tradingUnitId) {
    tabs.forEach((tab, index) => {
      if ((tab as any).tradingUnitId === tradingUnitId) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeId = (nextTab as any).id
        }
      }
    })
  }

  editableTabsValue.value = tradingUnitId
  editableTabs.value = tabs.filter((tab) => (tab as any).tradingUnitId !== tradingUnitId)
}


/** 显示审核不通过原因输入对话框 */
const showRejectDialog = async () => {

  try {
    const {value: reason} = await ElMessageBox.prompt('请输入审核不通过的原因', '审核不通过', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入原因',
      inputValidator: (val) => {
        if (!val || val.trim() === '') {
          return '请输入审核不通过的原因';
        }
        return true;
      }
    });

    if (reason) {
      formData.value.notPassing = reason;
      submitForm(2);
    }
  } catch (error) {
    // 用户取消操作
  }
};

// 根据 tab 的 id 返回对应的组件
const getTabComponent = (tradingUnitId) => {
  console.log(tradingUnitId, 'tradingUnitId')
  const orderStatus: any = route.query.status
  switch (orderStatus) {
    case '待确认':
      return daiquerenTable;
    case '已确认':
      return yiquerenTable;
    case '已完成':
      return detailsTable;
    case '已关闭':
      return detailsTable;
    case '未审核通过':
      return detailsTable;
    default:
      return yiwanchengTable;
  }
}

//获取用户信息
const userInfo = ref({})
const getUserInfo = async () => {
  const data = await getUserProfile()
  userInfo.value = data
  console.log(userInfo.value, 'userInfo.value')
}

// 时间戳格式化函数
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

/** 打开弹窗 */
const openData = async (type: any = formType.value, id: any = formData.value.id) => {
  console.log(type, id, 'type id')
  // 修改时，设置数据
  try {
    const formData = await DemandInfoMainApi.getDemandInfoMain(id)
    unitList.value = formData.demandInfoTradingUnitMapList
    tabChange(editableTabsValue.value)
  } finally {
  }

}

/** 打开弹窗 */
const open = async (type: any = formType.value, id: any = formData.value.id) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  mainId.value = id

  // getDemandStatus();
  // resetForm();
  getUserInfo();
  // getDemandStatus();
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DemandInfoMainApi.getDemandInfoMain(id)
      unitList.value = (formData.value as any).demandInfoTradingUnitMapList
      formDataList.value = (unitList.value as any).map(item => {
        // console.log(item, 'itemitem')
        return item.demandInfoTradingUnitDO[0]
      })
      // console.log(formDataList.value, 'formDataList.value')
      editableTabsValue.value = unitList.value[0].tradingUnitId
      tabChange(editableTabsValue.value)
    } finally {
      formLoading.value = false
    }
  }

}

const router = useRouter()

const back = () => {
  router.go(-1)
}
// 根据状态返回对应的颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case '待确认':
      return 'blue';
    case '已确认':
      return 'green';
    case '未审核通过':
      return 'red';
    case '已关闭':
      return 'gray';
    case '已完成':
      //淡绿色
      return '#90EE90';
    default:
      return 'black';
  }
};

const { proxy } = getCurrentInstance()
// 判断数据是否为空
const isEmpty = () => {
  //判断formData.value中的demandInfoTradingUnitMapList.demandInfoTradingUnitDO.notTrading和participateTradingId都不能为空
  if (formData.value.demandInfoTradingUnitMapList.length > 0) {
    for (let i = 0; i < formData.value.demandInfoTradingUnitMapList.length; i++) {
      const item = formData.value.demandInfoTradingUnitMapList[i];
      if (item.demandInfoTradingUnitDO.length > 0) {
        for (let j = 0; j < item.demandInfoTradingUnitDO.length; j++) {
          const child = item.demandInfoTradingUnitDO[j];
          //转让对象为空判断child.notTrading和child.participateTradingId只要填写了一个就行
          console.log(child, 'child.notTrading')
          if (child.notTrading == null) {
            if (child.participateTradingId == null) {
              //提示
              proxy.$showErrorMessage.error('请填写转让对象或请先点击查询')
              return false;
            } else {
              return true;
            }
          } else {
            return true;
          }
          //转让日期为空判断
          if (child.transferDateStart != null && child.transferDateEnd != null) {
            return true;
          } else {
            //提示
            message.error('请填写转让日期')
            return false;
          }
          //电量为空判断,必须最少填一个
          if (child.demandInfoTradingUnitInformationControllers.length > 0) {
            for (let k = 0; k < child.demandInfoTradingUnitInformationControllers.length; k++) {
              const son = child.demandInfoTradingUnitInformationControllers[k];
              if (son.electricity != null && son.electricityPrice != null) {
                return true;
              } else {
                //提示
                message.error('请最少填写一组电量和电价')
                return false;
              }
            }
          }
        }
      }
    }
  }
}

// 更新父组件中的 transferorImg 数据
const updateTransferorImgInParent = (tradingUnitId, transferorImg) => {
  if (formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId)) {
    formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId).demandInfoTradingUnitDO.forEach(unitDo => {
      unitDo.transferorImg = transferorImg.transferorImg;
    });
  }
  console.log(formData.value, 'formData.value')

  if (formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId)) {
    formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId).demandInfoTradingUnitDO.forEach(unitDo => {
      unitDo.transfereeImg = transferorImg.transfereeImg;
    })
  }
  if (formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId)) {
    formData.value.demandInfoTradingUnitMapList.find(item => item.tradingUnitId === tradingUnitId).demandInfoTradingUnitDO.forEach(unitDo => {
      unitDo.paymentImg = transferorImg.paymentImg;
    })
  }
};

//提交
const submitGongGong = async (type: number, isFresh: boolean = false) => {
  // 校验表单
  await formRef.value.validate()
  // console.log(formData.value, ' formData.value')
  const enum_ = {
    1: '已确认',
    2: '未审核通过',
    3: '已关闭',
    4: formData.value.status,
    5: '已完成',
  }
  formData.value.status = enum_[type]

  // console.log(formData.value, 'formData.value')
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as DemandInfoMainVO
    // const data = await DemandInfoMainApi.getDemandInfoMain(mainId.value)
    const data = formData.value as unknown as DemandInfoMainVO
    console.log(data, 'data')
    //修改data里的demandInfoTradingUnitMapList.demandInfoTradingUnitDO.transferorImg图片数字变成逗号分隔的字符串
    data.demandInfoTradingUnitMapList.forEach(item => {
      item.demandInfoTradingUnitDO.forEach(unitDo => {
        if (unitDo.transferorImg && typeof unitDo.transferorImg !== 'string') {
          unitDo.transferorImg = unitDo.transferorImg.join(',')
        }
        if (unitDo.transfereeImg && typeof unitDo.transfereeImg !== 'string') {
          unitDo.transfereeImg = unitDo.transfereeImg.join(',')
        }
        if (unitDo.paymentImg && typeof unitDo.paymentImg !== 'string') {
          unitDo.paymentImg = unitDo.paymentImg.join(',')
        }
      })
    })

    console.log(data, 'data')
    data.status = enum_[type]
    //判断必填数据不能为空
    if (formType.value === 'create') {
      await DemandInfoMainApi.createDemandInfoMain(data)
      if (isFresh) {
        refreshData()
      }
      message.success(t('common.createSuccess'))
    } else {
      await DemandInfoMainApi.updateDemandInfoMain(data)
      if (isFresh) {
        refreshData()
      }
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    if (!isFresh) {
      // 发送操作成功的事件
      emit('success')
      router.back()
    }
  } finally {
    formLoading.value = false
  }
}

// 定义刷新数据的方法
const refreshData = async () => {
  try {
    // 重新获取数据
    formData.value = await DemandInfoMainApi.getDemandInfoMain(mainId.value)
    unitList.value = (formData.value as any).demandInfoTradingUnitMapList
    formDataList.value = (unitList.value as any).map(item => {
      return item.demandInfoTradingUnitDO[0]
    })
    // editableTabsValue.value = unitList.value[0].tradingUnitId
    // 触发标签页切换，重新加载数据
    // tabChange(editableTabsValue.value)
    // message.success('刷新成功')
  } catch (error) {
    message.error('刷新失败，请稍后重试')
  }
}

// 交易单元选择对话框是否可见
const tradingUnitDialogVisible = ref(false);
// 所有交易单元列表
const allTradingUnits = ref([]);
// 已选择的交易单元 ID 列表
const selectedTradingUnitIds = ref([]);

// 获取该公司所有交易单元
const fetchAllTradingUnits = async () => {
  try {
    const params = {
      creator: formData.value.enterpriseId
    }
    const res = await TradingUnitApi.getTradingUnitListMe(params);
    allTradingUnits.value = res;
    console.log(allTradingUnits.value, 'allTradingUnits.value')
  } catch (error) {
    console.error('获取交易单元列表失败', error);
  }
};

// 显示交易单元选择对话框
const showTradingUnitDialog = () => {
  fetchAllTradingUnits();
  // 每次打开对话框时更新已选择的交易单元 ID 列表
  selectedTradingUnitIds.value = formData.value.demandInfoTradingUnitMapList.map(item => item.tradingUnitId);
  tradingUnitDialogVisible.value = true;
};

// 确认选择交易单元
const confirmTradingUnitSelection = () => {
  formData.value.demandInfoTradingUnitMapList = allTradingUnits.value.filter(unit =>
    selectedTradingUnitIds.value.includes(unit.id)
  );
  //formData.value.demandInfoTradingUnitMapList添加mainId字段
  formData.value.demandInfoTradingUnitMapList.forEach(item => {
    item.mainId = formData.value.id;
  })
  console.log(formData.value.demandInfoTradingUnitMapList, 'formData.value.demandInfoTradingUnitMapList')
  updateDemandinfoUnitApis(formData.value.demandInfoTradingUnitMapList)

  tradingUnitDialogVisible.value = false;

  //更新后刷新页面,从新调用接口获取数据，类似于刷新页面
  window.location.reload();
};
//修改需求单元
const updateDemandinfoUnitApis = async (params) => {
  await TradingUnitApi.updateDemandinfoUnitApi(params);
}

// 删除交易单元
const removeTradingUnit = (index: number) => {
  formData.value.demandInfoTradingUnitMapList.splice(index, 1);
};
// 根据时段返回对应的颜色
const getTimePeriodColor = (timePeriod: string) => {
  const peakPeriods = ['07:00-08:00','08:00-09:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00'];
  const offPeakPeriods = ['09:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00'];
  const valleyPeriods = ['00:00-01:00', '01:00-02:00', '02:00-03:00', '03:00-04:00', '04:00-05:00', '05:00-06:00', '06:00-07:00', '23:00-00:00'];

  if (peakPeriods.includes(timePeriod)) {
    //绿色
    return 'red'; // 高峰时段颜色
  } else if (offPeakPeriods.includes(timePeriod)) {
    return 'green'; // 平峰时段颜色
  } else if (valleyPeriods.includes(timePeriod)) {

    //橘色
    return 'orange'; // 低谷时段颜色
  }
};
// 更新父组件中 unitDo.feng 的值
const updateFengValueInParent = (tradingUnitId, row, item, refreshData_) => {
  if (formData.value.demandInfoTradingUnitMapList.find(
    mapItem => mapItem.tradingUnitId === tradingUnitId
  )) {
    const findIndex_ = formData.value.demandInfoTradingUnitMapList.findIndex(
      mapItem => mapItem.tradingUnitId === tradingUnitId
    );
    const findItem_ = formData.value.demandInfoTradingUnitMapList.find(
      mapItem => mapItem.tradingUnitId === tradingUnitId
    );
    formData.value.demandInfoTradingUnitMapList[findIndex_].demandInfoTradingUnitDO = findItem_.demandInfoTradingUnitDO.map(unitDo => {
      console.log(unitDo, 'unitDo')
      console.log(item, 'item')
      if (unitDo.id === item.id) {
        // item中demandInfoTradingUnitInformationControllers有24个代表24个时段，periodStart-periodEnd为一个时段，统计时段安装平，峰，谷统计和
        const dataTime = calculatePeakValleyFlat(item)

        let gu = unitDo.demandInfoTradingUnitInformationControllers.filter(ddss => getTimePeriodColor(ddss.periodStart+'-'+ddss.periodEnd) === 'green')
        gu = gu.reduce((total, cur) => {
          if (!isNaN(parseFloat(cur.electricity)) && !isNaN(parseFloat(cur.electricityPrice))) return total + (cur.electricity * cur.electricityPrice)
          return total
        }, 0)
        let ping = unitDo.demandInfoTradingUnitInformationControllers.filter(ddss => getTimePeriodColor(ddss.periodStart+'-'+ddss.periodEnd) === 'orange')
        ping = ping.reduce((total, cur) => {
          if (!isNaN(parseFloat(cur.electricity)) && !isNaN(parseFloat(cur.electricityPrice))) return total + (cur.electricity * cur.electricityPrice)
          return total
        }, 0)
        let feng = unitDo.demandInfoTradingUnitInformationControllers.filter(ddss => getTimePeriodColor(ddss.periodStart+'-'+ddss.periodEnd) === 'red')
        feng = feng.reduce((total, cur) => {
          if (!isNaN(parseFloat(cur.electricity)) && !isNaN(parseFloat(cur.electricityPrice))) return total + (cur.electricity * cur.electricityPrice)
          return total || 0
        }, 0)

        unitDo.feng = isNaN(parseInt(feng)) ? dataTime.peak : feng;
        unitDo.ping = isNaN(parseInt(ping)) ? dataTime.flat : ping;
        unitDo.gu = isNaN(parseInt(gu)) ? dataTime.valley : gu;
        unitDo.zong = isNaN(parseInt(gu + feng + ping)) ? dataTime.total : gu + feng + ping;

      }
      return unitDo
    });
    if (refreshData_) {
      refreshData()
    }
  }
};

// 统计峰、平、谷时段的电量总和
const calculatePeakValleyFlat = (item) => {
  let peak = 0;
  let flat = 0;
  let valley = 0;
  let total = 0;

  // 判断时段所属类型
  const getPeriodType = (period) => {
    const [start, end] = period.split('-');
    const startTime = new Date(`1970-01-01T${start}:00`).getTime();
    const endTime = new Date(`1970-01-01T${end}:00`).getTime();

    const peakStart1 = new Date(`1970-01-01T07:00:00`).getTime();
    const peakEnd1 = new Date(`1970-01-01T08:00:00`).getTime();
    const peakStart2 = new Date(`1970-01-01T17:00:00`).getTime();
    const peakEnd2 = new Date(`1970-01-01T22:00:00`).getTime();

    const valleyStart = new Date(`1970-01-01T09:00:00`).getTime();
    const valleyEnd = new Date(`1970-01-01T16:00:00`).getTime();

    if ((startTime >= peakStart1 && endTime <= peakEnd1) || (startTime >= peakStart2 && endTime <= peakEnd2)) {
      return 'peak';
    } else if (startTime >= valleyStart && endTime <= valleyEnd) {
      return 'valley';
    } else {
      return 'flat';
    }
  };

  item.demandInfoTradingUnitInformationControllers.forEach(controller => {
    const electricity = parseFloat(controller.electricity) || 0;
    total += electricity;
    const periodType = getPeriodType(controller.periodStart + '-' + controller.periodEnd);
    switch (periodType) {
      case 'peak':
        peak += electricity;
        break;
      case 'valley':
        valley += electricity;
        break;
      case 'flat':
        flat += electricity;
        break;
    }
  });

  return { peak, flat, valley, total };
};

onMounted(() => {
// (orderStatus as any).value = route.query.orderStatus
  open(formType.value, route.query.id)

})
</script>

<style lang="scss" scoped>

.label {
  width: 100px;
  text-align: center;
  padding: 8px;
  color: #fff;
  font-weight: bold;
}

.bg-color {
  background-color: #409eff;
}

.font-color {
  color: #409eff;;
}

:deep(.el-tabs__item.is-active), :deep(.el-tabs__item:hover) {
  background-color: #409eff;;
  color: #fff;
}

:deep(.el-form-item__label) {
  display: flex;
  justify-content: flex-start;
  color: #409eff;;
  white-space: nowrap;
  font-size: 18px;
}

.d-form-item {
  width: 100%;
}

.bd-dj {
  width: 100%;
  padding: 8px 12px;
  box-sizing: border-box;
  border: 1px solid #409eff;;
  margin: 20px 0;
  // 调整最大高度，可根据需求修改
  max-height: 400px;
  overflow-y: auto;
}

.page-demand {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
}

.el-tabs__nav-wrap::after {
  height: 1px;
}

.el-input__wrapper,
.el-textarea__wrapper {
  box-shadow: 0 0 0 1px #dcdfe6;
}

.el-input__wrapper:hover,
.el-textarea__wrapper:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.el-input__wrapper.is-focus,
.el-textarea__wrapper.is-focus {
  box-shadow: 0 0 0 1px #409eff;
}
.label.bg-color {
  margin-bottom: 0; // 去除底部外边距
}

.bd-dj {
  margin-top: 0; // 去除顶部外边距
}


.small-height-form-item {
  margin-bottom: 4px; // 减小表单项底部外边距
}

.small-height-input {
  padding: 4px 8px; // 减小输入框内边距
  font-size: 16px; // 减小字体大小
  line-height: 1.2; // 减小行高
}

.small-height-text {
  font-size: 16px; // 减小字体大小
  line-height: 1.2; // 减小行高
}

.custom-label-size {
  :deep(.el-form-item__label) {
    font-size: 16px; // 设置字体大小为 8px
  }
}
.custom-h3-size {
  font-size: 16px;
}

.el-form-item--default {
  margin-bottom: 0;
  .el-form-item__content {
    height: 26px;
    line-height: 26px;
  }
}
.no-wrap {
  white-space: nowrap; /* 禁止文本换行 */
}
</style>
